package security.SecurityUtil.login;/**
 * @Auther: liyipeng
 * @Date: 2020/1/9 09:34
 * @Description:
 */

import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import util.Object2JsonString2ObjectUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * <p>类名: MyUsernamePasswordAuthenticationFilter</p>
 * <p>描述:实现自己的登录过滤器，直接继承security的登录过滤器，该过滤器为抽象类</p>
 * <p>创建人: liyp</p>
 * <p>创建时间: 2020/1/9 9:34</p>
 * <p>@version 2.0  </p>
 * <p>修改内容: ......</p>
 * <p>修改说明: ......</p>
 * <p>修改时间: ......</p>
 * <p>修改人: ......</p>
 * <p>每次修改，请增加上述修改信息说明</>
 */
public class MyUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private static final String LOGIN_URL = "/login";
    private AuthenticationManager authenticationManager;

    private static RequestMatcher requestMatcher = new OrRequestMatcher(
            // new AntPathRequestMatcher(OAUTH_TOKEN_URL, "GET"),
            new AntPathRequestMatcher(LOGIN_URL, "POST")
    );

    //拦截是post方法的登录url
    public MyUsernamePasswordAuthenticationFilter(){
        //拦截url为 "/login" 的POST请求
        super(requestMatcher);

    }

    /**
     *
     * 功能描述：此为登录拼接方式
     * 作   者： liyp
     * 创建时间： 2020/1/9 9:45
     * 参数: [httpServletRequest, httpServletResponse]
     *  返回值： org.springframework.security.core.Authentication
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException {
        String body = StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8"));
        String username = null, password = null;
        LoginModel loginModel = null;
        if(StringUtils.hasText(body)) {
            loginModel = Object2JsonString2ObjectUtil.jsonString2Object(body, new TypeReference<LoginModel>() {
            },"yyyy-MM-dd");
        }
        username = loginModel.getUsername().trim();
        //封装到token中提交
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, loginModel.getPassword());
        return this.getAuthenticationManager().authenticate(authRequest);
    }


}
